package com.jqsoft.launcher.activity.personnelInformationList;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.PersonnelInformation;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.util.CommonUtil;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**人员信息列表
 * @author gujunqi
 * date：2014-2-27 
 */
public class PersonnelInformationActivity extends JQActivity implements OnClickListener,OnScrollListener  {
	private final String tag = "PersonnelInformationActivity";
	private ListView listview;// 列表
	private ListAdapter adapter;

	private CheckBox xzCheckbox ,current_xzCheckbox;
	private Button chaxuan_btn,queding_btn,totalcount_bt;
	private EditText name_et,dangan_num_et,shengfenzheng_et;
	private String content;
	private List<PersonnelInformation> infoList = new ArrayList<PersonnelInformation>();
	private boolean notfirstTime=false,isThreadrun=false;
	private long allcount=0;
	
	private View moreView;
	private LinearLayout progressBar_ll; // 更多等待层
	private Button moreButton;
	
	private PersonnelInformation xuanzhong_tiao;
	private String sex; //判断母亲还是父亲
	@Override
	protected int getContentLayout() {
		return R.layout.personnel_information_list;
	}

	@Override
	protected void initGui() {
		listview = (ListView) findViewById(R.id.hbp_diagnosis_lv);
		chaxuan_btn=(Button) findViewById(R.id.chaxuan_btn);
		chaxuan_btn.setOnClickListener(PersonnelInformationActivity.this);
		queding_btn=(Button) findViewById(R.id.queding_btn);
		queding_btn.setOnClickListener(PersonnelInformationActivity.this);
		totalcount_bt=(Button) findViewById(R.id.totalcount_bt);
		dangan_num_et=(EditText) findViewById(R.id.dangan_num_et);
		name_et=(EditText) findViewById(R.id.name_et);
		shengfenzheng_et=(EditText) findViewById(R.id.shengfenzheng_et);

	

	}

	@Override
	protected void initAction() {
		setGoBack();
		listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				PersonnelInformation obj = (PersonnelInformation) listview.getItemAtPosition(position);

					xuanzhong_tiao= obj;
				xzCheckbox=(CheckBox) view.findViewById(R.id.xuanzhong_cb);
				for(int i=0;i<infoList.size();i++){
					infoList.get(i).setCheck(false);
				}
				obj.setCheck(true);
				if(current_xzCheckbox!=null){
					current_xzCheckbox.setChecked(false);}
					xzCheckbox.setChecked(true);
					current_xzCheckbox=xzCheckbox;
					adapter.notifyDataSetChanged();
			}
			
		});
		listview.setOnScrollListener(this);	
	}

	@Override
	protected void initData() {
		Intent intent = getIntent();
        Bundle bundle=intent.getExtras();
        if(bundle!=null){
        	sex = bundle.getString("sex");
        }
        setTitle("人员信息列表");
		moreView = getLayoutInflater().inflate(
				R.layout.finance_fund_pagination_more, null);
		moreButton = (Button) moreView.findViewById(R.id.loadMore);
		moreButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			      if(notfirstTime&&(allcount>infoList.size())&&!isThreadrun)
			        {
			    	  moreButton.setVisibility(View.GONE);
			    	  progressBar_ll.setVisibility(View.VISIBLE);
			    	  new Thread(sendable).start();
			        }
			}
		});
		progressBar_ll = (LinearLayout) moreView.findViewById(R.id.progressBar_ll);
	}

private Handler myhandler = new Handler() {
	public void handleMessage(Message msg) {
		switch (msg.what) {
		case Constant.MSG_LOAD_OVER:
			adapter = new ListAdapter();
			notfirstTime=true;
			if(!(infoList.size()==allcount||allcount==0||infoList.size()<=0)){
//				listview.removeFooterView(moreView);
				listview.addFooterView(moreView);
			}
			listview.setAdapter(adapter);
			String count="共计"+allcount+"条）";
			totalcount_bt.setText("（已加载"+infoList.size()+"条/"+count);
			dismissrogressBar();
			break;
		case Constant.SHOW_UPDATE:
			totalcount_bt.setText("（已加载"+infoList.size()+"条/"+"共计"+allcount+"条）");
			if(infoList.size()>=allcount){
				 listview.removeFooterView(moreView);
			}else{
				progressBar_ll.setVisibility(View.GONE);
		    	  moreButton.setVisibility(View.VISIBLE);
			}
			adapter.notifyDataSetChanged();
//				dismissrogressBar();
			break;
		}
		isThreadrun=false;
	}
};
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
	// TODO Auto-generated method stub
	
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
		int visibleItemCount, int totalItemCount) {
//	   dismissPopupWindow();
	      if(firstVisibleItem+visibleItemCount==totalItemCount&&notfirstTime&&(allcount>infoList.size())&&!isThreadrun)
	        {
//	    	  loadWaitPanel();
//	        	//开线程去下载网络数据
//	    	  new Thread(sendable).start();
	        }
		}
// 请求服务器
		private Runnable sendable = new Runnable() {
			public void run() {
				isThreadrun=true;
				String methodName = BphsURL.getCommonPath("GetPersonInfoManageData_METHOD");
				String requestUrl = BphsURL.getCommonPath("GetPersonInfoManageData_URL");
//				 String requestUrl = "http://192.168.44.163:9099/WebService/Andrews/PersonInfoWebService.asmx";
				Log.i(tag, "查询:content" + requestUrl);
//				String methodName="GetPersonInfoManageData";
				JSONObject data = new JSONObject();
//				{"sAreaCode":"340800","iCurrentPageIndex":"1","iPageSize":"10"}
				try {
					UserLoginInfo info = UserLoginInfo.getInstances();
					data.put("sAreaCode", info.getsManagementDivisionCode());// 
					data.put("iCurrentPageIndex", "1"); 
					data.put("iPageSize", "10"); // 
					data.put("sNo", dangan_num_et.getText()); // 
					data.put("sPersonName", name_et.getText()); // 
					data.put("sCardNo", shengfenzheng_et.getText()); // 
					if("2".equals(sex)){
						data.put("sSexcode", "2"); // 获取母亲信息
				    }else if("1".equals(sex)){
				    	data.put("sSexcode", "1"); // 获取父亲信息
				    }
					data.put("sAgeStart", "16"); // 
					data.put("sAgeEnd", "45"); // 
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
				content = WebServiceUtils.requestByParams(methodName, data.toString(), requestUrl);
				if (StringUtils.isNotBlank(content)) {
					  try {
							Log.i(tag, "返回的查询结果"+content);
//						 String result= content.replaceAll("\\\\", "");
//							Log.i(tag, "返回的查询结果"+result);
						JSONObject json = new JSONObject(content);
//						Log.i(tag, "返回的查询结果"+result);"AllCount":0,
//						allcount= 28;
						allcount= json.getLong("AllCount");
					JSONObject jo = new JSONObject(json.getString("Data"));
					 JSONArray jsonArray = (JSONArray) jo.get("Table");
			            for (int i = 0; i < jsonArray.length(); ++i) {
			                JSONObject o = (JSONObject) jsonArray.get(i);			            
			                PersonnelInformation info =new PersonnelInformation(o.getString("sPersonID"),o.getString("sNo"), o.getString("sPersonName"), o.getString("sSexName"),
			                		o.getString("dBirthday"),o.getString("sCardNo"), 
			                		o.getString("sHouseholdTypeName"), 
			                		o.getString("sInputDeptName"),
			                		o.getString("sAreaProvinceName")+o.getString("sAreaCityName")+ 
			                		o.getString("sAreaCountryName")+o.getString("sAreaTownName")+ o.getString("sAreaVillageName")+o.getString("sAreaGroup"),o.getString("sPhone"), o.getString("IsECGTB"));
			    			infoList.add(info);
			            }} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					  if(notfirstTime){
						  myhandler.sendEmptyMessage(Constant.SHOW_UPDATE);
					  }else{
					myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);}
				}
			}	
		};

@Override
public void onClick(View v) { 
	switch (v.getId()) {
	case R.id.chaxuan_btn://查询按钮
		if(infoList.size()>0){
		listview.removeFooterView(moreView);}
		infoList.clear();
		allcount=0;
		notfirstTime=false;
		loadWaitPanel();
		new Thread(sendable).start();
		return;
	case R.id.queding_btn://确定按钮
		if(current_xzCheckbox==null){
			MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
			return;
		}
		if(xuanzhong_tiao!=null){
			//设置当前activity被关闭的时候的结果数据
			Intent data = new Intent();
			data.putExtra("name", xuanzhong_tiao.getsPersonName());
			data.putExtra("dBirthday", xuanzhong_tiao.getdBirthday());
			data.putExtra("sPhone", xuanzhong_tiao.getsPhone());
			setResult(RESULT_OK, data);
			//关闭当前的activity
			PersonnelInformationActivity.this.finish();
		}
		return;
	case R.id.ll_popup_xuanzhong:
		if(current_xzCheckbox!=null){
		current_xzCheckbox.setChecked(false);}
		xzCheckbox.setChecked(true);
		current_xzCheckbox=xzCheckbox;
		break;
	case R.id.ll_popup_chakan:
		break;
	case R.id.ll_popup_quxiao:
		break;
	}
}
	
public boolean onKeyDown(int keyCode, KeyEvent event) {
	Log.d(tag, "屏蔽 home,back,menu键keyCode:" + keyCode);
	if (keyCode == KeyEvent.KEYCODE_BACK) {
		Log.d(tag, "BACK键捕获。to BACK");
		act.finish();
		act.overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		return true;
	}
	if (KeyEvent.KEYCODE_HOME == keyCode) {
		Log.d(tag, "home键捕获。to home");
		toHome();
		return true;
	}
	return super.onKeyDown(keyCode, event);
}

private class ListAdapter extends BaseAdapter {

	public int getCount() {
		return infoList.size();
	}

	public Object getItem(int position) {
		return infoList.get(position);
	}

	public long getItemId(int position) {

		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = LayoutInflater.from(act);

			convertView = inflater.inflate(R.layout.personnel_information_item, null);
			TextView dangan_num_tv = (TextView) convertView
					.findViewById(R.id.dangan_num_tv);
			TextView name_tv = (TextView) convertView
					.findViewById(R.id.name_tv);
			TextView sex_tv = (TextView) convertView
					.findViewById(R.id.sex_tv);
			TextView age_tv = (TextView) convertView
					.findViewById(R.id.age_tv);
			TextView shengfenzheng_tv = (TextView) convertView
					.findViewById(R.id.shengfenzheng_tv);
			TextView changzhu_type_tv = (TextView) convertView
					.findViewById(R.id.changzhu_type_tv);
			TextView luru_danwei_tv = (TextView) convertView
					.findViewById(R.id.luru_danwei_tv);

			TextView jiating_address_tv = (TextView) convertView
					.findViewById(R.id.jiating_address_tv);

			CheckBox cb= (CheckBox) convertView
					.findViewById(R.id.xuanzhong_cb);

		dangan_num_tv.setText(infoList.get(position)
				.getsNo());
		name_tv.setText(infoList.get(position)
				.getsPersonName());
		sex_tv.setText(infoList.get(position)
				.getsSexName());
		
		age_tv.setText(CommonUtil.calcAge2(infoList.get(position)
				.getdBirthday())+"");
		shengfenzheng_tv.setText(infoList.get(position)
				.getsCardNo());
		changzhu_type_tv.setText(infoList.get(position)
				.getsHouseholdTypeName());
		luru_danwei_tv.setText(CommonUtil.String2date(infoList.get(position)
				.getsInputDeptName()));

		jiating_address_tv.setText(infoList.get(position)
				.getJiating_address());

		cb.setChecked(infoList.get(position)
				.isCheck());
		return convertView;
	}
}
}
